package org.chris.ui.componets;

import org.chris.ui.activities.AquarianMain;
import org.chris.utils.ApplicationUtils;
import org.chris.utils.Constants;
import org.chris.utils.UrlUtils;

import android.graphics.Bitmap;
import android.webkit.WebView;
import android.webkit.WebViewClient;

/**
 * Convenient extension of WebViewClient.
 */
public class CustomWebViewClient extends WebViewClient {

	AquarianMain mAquarianMain;

	public CustomWebViewClient(AquarianMain aquarianMain) {
		super();
		mAquarianMain = aquarianMain;
	}

	@Override
	public void onPageFinished(WebView view, String url) {
		((CustomWebView) view).notifyPageFinished();
		mAquarianMain.onPageFinished(url);

		super.onPageFinished(view, url);
	}

	@Override
	public void onPageStarted(WebView view, String url, Bitmap favicon) {

		// Some magic here: when performing WebView.loadDataWithBaseURL, the url
		// is "file:///android_asset/startpage,
		// whereas when the doing a "previous" or "next", the url is
		// "about:start", and we need to perform the
		// loadDataWithBaseURL here, otherwise it won't load.
		if (url.equals(Constants.URL_ABOUT_START)) {
			view.loadDataWithBaseURL("file:///android_asset/startpage/",
					ApplicationUtils.getStartPage(view.getContext()),
					"text/html", "UTF-8", "about:start");
		}

		((CustomWebView) view).notifyPageStarted();
		mAquarianMain.onPageStarted(url);

		super.onPageStarted(view, url, favicon);
	}

	@Override
	public boolean shouldOverrideUrlLoading(WebView view, String url) {

		// If the url is not from GWT mobile view, and is in the mobile view
		// url list, then load it with GWT.
		if ((!url.startsWith(Constants.URL_GOOGLE_MOBILE_VIEW_NO_FORMAT))
				&& (UrlUtils.checkInMobileViewUrlList(view.getContext(), url))) {

			String newUrl = String
					.format(Constants.URL_GOOGLE_MOBILE_VIEW, url);
			view.loadUrl(newUrl);
			return true;

		} else {
			((CustomWebView) view).resetLoadedUrl();
			mAquarianMain.onUrlLoading(url);
			return false;
		}
	}

	private boolean isExternalApplicationUrl(String url) {
		return url.startsWith("vnd.") || url.startsWith("rtsp://")
				|| url.startsWith("itms://") || url.startsWith("itpc://");
	}

}
